#import "CTVerifyCodeVC.h"
#import "HWTFCursorView.h"
#import "MJTimer.h"
#import "CTSetPwdVC.h"
@interface CTVerifyCodeVC ()
@property (nonatomic ,strong) UILabel *titleLabel;
@property (nonatomic ,strong) UILabel *subTitleLabel;
@property (strong,nonatomic) HWTFCursorView *msgCodeView;
@property (nonatomic ,strong) UIButton *msgCodeBtn;
@property (nonatomic ,strong) UIButton *voiceCodeBtn;
@property (nonatomic ,assign) NSInteger count;
@property (copy, nonatomic) NSString *task;
@property (nonatomic ,copy) NSString *verifyToken;
@property (nonatomic ,copy) NSString *currentCodeType;
@property (nonatomic ,copy) NSString *captchaCode;
@property (nonatomic ,copy) NSString *captchaId;
@end
@implementation CTVerifyCodeVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setConstrains];
    [self getCodeWithType:@"0"];
    [self obserRAC];
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kpage_login,
        @"elementUniqueIdentifier"  : kpage_login,
        @"referenceIdentification" : @"",
    };
    [CTUploadManager ct_uploadType:CTUploadTypePage data:data];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MJTimer cancelTask:self.task];
}
- (void)setUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self ct_showCustomerNavBarWithType:WBNavBarTypeNormal];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.subTitleLabel];
    [self.view addSubview:self.msgCodeView];
    [self.view addSubview:self.msgCodeBtn];
    [self.view addSubview:self.voiceCodeBtn];
    [self.view becomeFirstResponder];
}
- (void)setConstrains {
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Ratio(24));
        make.top.mas_equalTo([UIDevice ct_fullNavHeight]+Ratio(30));
    }];
    [self.subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Ratio(24));
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(Ratio(24));
    }];
    [self.msgCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.subTitleLabel.mas_bottom).offset(Ratio(41));
        make.left.mas_equalTo(Ratio(24));
        make.right.mas_equalTo(Ratio(-24));
        CGFloat width = (kScreenWidth-Ratio(48)-Ratio(60))/6;
        make.height.mas_equalTo(width);
    }];
    [self.msgCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.msgCodeView.mas_bottom).offset(Ratio(10));
        make.right.mas_equalTo(Ratio(-24));
    }];
    [self.voiceCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.msgCodeView.mas_bottom).offset(Ratio(10));
        make.left.mas_equalTo(Ratio(24));
    }];
}
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.numberOfLines = 1;
        _titleLabel.font = [UIFont systemFontOfSize:Ratio(20) weight:UIFontWeightBold];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.text = @"Please enter the verification code";
    }
    return _titleLabel;
}
- (UILabel *)subTitleLabel {
    if (!_subTitleLabel) {
        _subTitleLabel = [[UILabel alloc] init];
        _subTitleLabel.numberOfLines = 1;
        _subTitleLabel.font = [UIFont systemFontOfSize:Ratio(11) weight:UIFontWeightMedium];
        _subTitleLabel.textColor = [UIColor colorFF8724];
        _subTitleLabel.textAlignment = NSTextAlignmentLeft;
        NSString *holderText = @"The verification code has been sent to";
        NSString *allText = [NSString stringWithFormat:@"%@ %@",holderText, [[CTUserManager shareManager].userModel.wirelessDeviceNumber maskedPhoneNumber]];
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:allText];
        [placeholder addAttributes:@{NSFontAttributeName:
                                         [UIFont systemFontOfSize:Ratio(11)],
                                     NSForegroundColorAttributeName:[UIColor color77777D]
                                   }
                             range:NSMakeRange(0, holderText.length)];
        _subTitleLabel.attributedText = placeholder;
    }
    return _subTitleLabel;
}
- (HWTFCursorView *)msgCodeView
{
    if (_msgCodeView == nil) {
        _msgCodeView = [[HWTFCursorView alloc] initWithCount:6 margin:Ratio(12.5) borderColor:[UIColor colorA4A5AC]];
    }
    return _msgCodeView;
}
- (UIButton *)msgCodeBtn
{
    if (!_msgCodeBtn) {
        _msgCodeBtn = [[UIButton alloc] init];
        [_msgCodeBtn setBackgroundColor:[UIColor whiteColor]];
        _msgCodeBtn.userInteractionEnabled = YES;
        [_msgCodeBtn setTitle:@"Resend" forState:UIControlStateNormal];
        [_msgCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:Ratio(13)]];
        [_msgCodeBtn setTitleColor:[UIColor colorFF6C2E] forState:UIControlStateNormal];
        [_msgCodeBtn addTarget:self action:@selector(msgCodeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _msgCodeBtn;
}
- (void)msgCodeBtnClick {
    [self getCodeWithType:@"0"];
}
- (UIButton *)voiceCodeBtn
{
    if (!_voiceCodeBtn) {
        _voiceCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_voiceCodeBtn setBackgroundColor:[UIColor whiteColor]];
        _voiceCodeBtn.userInteractionEnabled = YES;
        [_voiceCodeBtn setTitle:@"Voice code" forState:UIControlStateNormal];
        [_voiceCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:Ratio(13)]];
        [_voiceCodeBtn setTitleColor:[UIColor colorFF6C2E] forState:UIControlStateNormal];
        _voiceCodeBtn.hidden = YES;
        [_voiceCodeBtn addTarget:self action:@selector(voiceCodeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _voiceCodeBtn;
}
- (void)voiceCodeBtnClick {
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kbtn_login_unreceived,
        @"elementUniqueIdentifier"  : kbtn_login_unreceived,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
    [self getCodeWithType:@"1"];
}
#pragma mark - get code
- (void)getCodeWithType:(NSString *)codeType {
    self.currentCodeType = codeType;
    NSString *phoneNM = [CTUserManager shareManager].userModel.wirelessDeviceNumber;
    NSString *mobile = [CTEncryptTool encryptInfo:returnBeNil([CTUserManager shareManager].userModel.wirelessDeviceNumber)];
    NSDictionary *paramDic = @{ @"wirelessDeviceNumber" : returnBeNil(mobile),
                                @"codeClassification" : returnBeNil(codeType),
                                @"cipherToken" : returnBeNil(self.codeToken),
                                @"processActionType" : @(self.operationType),
                                @"visualRecordId" : @"",
                                @"imageVerificationKey" : returnBeNil(self.captchaCode),
                                @"userIprAddress" : @"",
                                @"sliderVerificationStatus" : @"",
                                @"geetestSecurityQuery" : @"",
                                @"geetestAuthenticationResult" : @"",
                                @"geetestSecurityCode" : @"",
                                @"externalCommunicationChannel" : @"",
                                @"userGroup" : @"",
                                @"retreatPhone" : @"",
                                @"validationNumericCode" : @"",
                                @"imageStatus" : @"",
    };
    [self.view showLoading];
    __weak typeof(self) weakself = self;
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/waveHeight", CTPathTypePost, nil) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
            if (operation.showGraphicCode) {
                THTipInputView *inputView = [[THTipInputView alloc] initWithComplete:^(NSString * _Nonnull codeValue, NSString * _Nonnull captcheId) {
                    self.captchaCode = codeValue;
                    self.captchaId = captcheId;
                    [self.view showText:@"Please resend the verification code"];
                }];
                [inputView show];
            }
        } else {
            [self.view showText:@"The verification code is sent successfully."];
            if (responseObject[@"matterContent"] != nil) {
                NSDictionary *dic = responseObject[@"matterContent"];
                self.verifyToken = dic[@"cipherToken"];
            }
            [self starTimer];
        }
    }];
}
#pragma mark - ARC
- (void)obserRAC{
    @weakify(self);
    [RACObserve(self.msgCodeView, code) subscribeNext:^(id x) {
        @strongify(self);
        if (self.msgCodeView.code.length == 6) {
            if (self.operationType == CTOperationTypeRegister) {
                [self verifyCode];
            } else if (self.operationType == CTOperationTypeOldPhoneLogin) {
                [self loginRequest];
            }
        }
    }];
}
#pragma mark - msm check
- (void)verifyCode {
    NSString *mobile = [CTUserManager shareManager].userModel.wirelessDeviceNumber;
    [self.view showLoading];
    [CTService verifyCodeWithMobile:returnBeNil(mobile)
                         verifyCode:returnBeNil(self.msgCodeView.code)
                        verifyToken:returnBeNil(self.verifyToken)
                          codeToken:returnBeNil(self.codeToken)
                      operationType:@(self.operationType)
                              block:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
            if (responseObject[@"matterContent"] != nil) {
                NSDictionary *dic = responseObject[@"matterContent"];
                NSNumber * status = dic[@"operationalStatus"];
                if (status.integerValue == 1) {
                    CTSetPwdVC *enterPwdVC = [[CTSetPwdVC alloc] init];
                    enterPwdVC.codeToken = self.verifyToken;
                    enterPwdVC.verifyCode = self.msgCodeView.code;
                    [self.navigationController pushViewController:enterPwdVC animated:YES];
                } else {
                    [self.view showInfoText:@"Verification failure"];
                }
            } else {
                [self.view showInfoText:@"Verification failure"];
            }
        }
    }];
}
- (void)loginRequest {
    [self.view showLoading];
    [CTService loginWithMobile:returnBeNil([CTUserManager shareManager].userModel.wirelessDeviceNumber)
                      password:returnBeNil(self.pwdStr)
                     codeToken:returnBeNil(self.codeToken)
                 operationType:@(self.operationType)
                    verifyCode:returnBeNil(self.msgCodeView.code)
                   verifyToken:returnBeNil(self.verifyToken)
                   captchaCode:@""
                     captchaId:@""
                   secondLogin:@(0)
                         block:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
        }
    }];
}
- (void)starTimer {
    self.count = 60;
    self.task = [MJTimer execTask:self
                         selector:@selector(countdown)
                            start:0.0
                         interval:1.0
                          repeats:YES
                            async:NO];
}
- (void)countdown {
    UIButton *button;
    if ([self.currentCodeType isEqualToString:@"0"]) {
        button = self.msgCodeBtn;
    } else {
        button = self.voiceCodeBtn;
    }
    if (self.count>0) {
        self.count --;
        button.userInteractionEnabled = NO;
        [button setTitleColor:[UIColor colorWithHexString:@"#B5BAC4"] forState:UIControlStateNormal];
        NSString *str = [NSString stringWithFormat:@"%@s",@(self.count).stringValue];
        [button setTitle:str forState:UIControlStateNormal];
    } else {
        [MJTimer cancelTask:self.task];
        [button setTitleColor:[UIColor colorFF6C2E] forState:UIControlStateNormal];
        button.userInteractionEnabled = YES;
        if ([self.currentCodeType isEqualToString:@"0"]) {
            self.voiceCodeBtn.hidden = NO;
            [button setTitle:@"Resend" forState:UIControlStateNormal];
        } else {
            [button setTitle:@"Voice code" forState:UIControlStateNormal];
        }
    }
}
@end
